package pl.mchaniewski.ryneczek.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import pl.mchaniewski.ryneczek.dao.CompanyDao;
import pl.mchaniewski.ryneczek.pojo.Company;

@Repository("companyDao")
@Transactional(readOnly = true)
public class HibernateCompanyDao extends HibernateGenericDao<Company, Integer>
        implements CompanyDao {

    @SuppressWarnings("unchecked")
    @Override
    public List<Company> loadAll() {
        String queryString = "from Company";
        Query query = getEntityManager().createQuery(queryString);

        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Company> findByName(String name) {
        String queryString = "from Company where name=:name";
        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("name", name);

        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Company> findDistinctInPortfolio(Integer portfolioid) {
        String queryString = "select distinct o.company from Order o where o.portfolio.portfolioid=:id";
        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("id", portfolioid);

        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Company> findDistinctInPortfolio(Integer portfolioid,
            boolean wasInLastUpdate) {
        String queryString = "select distinct o.company from Order o where o.portfolio.portfolioid=:id and o.company.wasInLastUpdate=:wasInLastUpdate";
        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("id", portfolioid);
        query.setParameter("wasInLastUpdate", Boolean.valueOf(wasInLastUpdate));

        return query.getResultList();
    }

}
